﻿(function () {
    var myApp = angular.module('MyControllers');

    // 配置所需控制器
    myApp.controller('loginController', ['$scope', '$http', '$modal', 'configService', 'utils', function ($scope, $http, $modal, service, utils) {
        var srv = service.loginSrv;

        $scope.checkForUpdates = function () {
            $modal.open({
                templateUrl: '/App/views/Config/CheckForUpdates.html',
                controller: 'checkForUpdates',
                backdrop: 'static',
                keyboard: false,
                resolve: {
                    params: function () {
                        return 0;
                    }
                }
            });
        };

        // 是否需要检测版本更新
        $scope.isNeedCheck = isNeedCheckVersion;
        $scope.login = function () {

            if ($('form#loginForm').valid()) {
                $scope.loadingState = true;
                srv.login($scope.username, $scope.password).success(function (data) {
                    commonFun.setCookie('account',$scope.username);
                    $scope.loadingState = false;
                    if (data.resultType == 'Success') {
                        var br = navigator.userAgent.toLowerCase();
                        var isIe = br.indexOf('trident') > -1 || br.indexOf('msie') > -1;

                        if (!isIe) {
                            var modal = utils.confirm({
                                msg: "当前浏览器并不是IE浏览器，刷卡功能将不能使用。确认继续访问？",
                                ok: '确认',
                                cancel: '取消'
                            });
                            modal.result.finally(function (a) {
                                // do something ...
                            });
                            modal.result.then(function (result) {
                                if (result) {
                                    utils.notify('登录成功，正在跳转...', 'success');
                                    window.location.href = '/Home/Index?account=' + $scope.username;
                                }
                            });
                        } else {
                            window.location.href = '/Home/Index?account=' + $scope.username;
                        }

                    } else {
                        utils.notify(data.message, 'warning');
                    }
                });
            }
        }

        $scope.examSiteConfig = function () {
            $modal.open({
                templateUrl: '/App/views/Config/ExamSiteConfig.html',
                controller: 'configSteps',
                backdrop: 'static',
                keyboard: false,
                resolve: {
                    params: function () {
                        return 0;
                    }
                }
            });
        };

        $scope.curAppConfig = function () {
            $modal.open({
                templateUrl: '/App/views/Config/CurAppConfig.html',
                controller: 'curAppConfig',
                backdrop: 'static',
                keyboard: false,
                resolve: {
                    params: function () {
                        return $scope.siteId;
                    }
                }
            });
        };

        $scope.$root.$on('login', function (event, data) {
            if (data) {
                if (data.code) {
                    $scope.username = data.code;
                    $('#username').val(data.code);
                }
                if (data.pwd) {
                    $scope.password = data.pwd;
                    $('#password').val(data.pwd);
                }
            }

            $scope.login();
        });

        $scope.$root.$on('login2', function (event, data) {
            if (data) {
                $scope.isNeedCheck = false;
                $scope.login();
            }
        });
    }]);

    // 版本更新
    myApp.controller('checkForUpdates', ['$scope', '$routeParams', '$modalInstance', 'configService', 'utils', 'params', '$filter', function ($scope, $routeParams, $modalInstance, service, utils, params, $filter) {
        var srv = service.updateSrv;

        var methods = {
            checkForOnLine: function () {
                $scope.loadingState = true;
                $scope.message = "正在检测连网状态...";

                srv.checkForOnLine().success(function (data) {
                    $scope.loadingState = false;

                    if (data) {
                        $scope.checkForUpdate();
                    } else {
                        utils.notify('当前为未连网状态，不能检测最新版本...', 'warning');
                        $scope.againLogin();
                    }
                });
            },
            checkForUpdate: function () {
                $scope.loadingState = true;
                $scope.message = "正在检测最新版本...";

                srv.checkForUpdate().success(function (data) {
                    $scope.loadingState = false;

                    if (!data.IsNewest) {
                        if (!data.IsAllowUpdate) {
                            utils.notify('当前时间不能进行更新版本...', 'warning');
                            $scope.againLogin();
                        } else {
                            if (!data.IsNecessary) {
                                $scope.updateForSimple(data.NewestVersion);
                            } else {
                                $scope.updateForNecessary(data.NewestVersion);
                            }
                        }
                    } else {
                        //tils.notify('当前系统为最新版本，无需更新...', 'warning');
                        $scope.againLogin();
                    }
                });
            },
            updateForSimple: function (version) {
                $scope.loadingState = true;
                $scope.message = "正在进行更新...";

                srv.updateForSimple(version).success(function (data) {
                    $scope.loadingState = false;

                    if (data.result) {
                        utils.notify(data.mesasge, 'success');
                        $scope.againLogin();
                    } else {
                        utils.notify(data.mesasge, 'warning');
                    }
                });
            },
            updateForNecessary: function (version) {
                $scope.loadingState = true;
                $scope.message = "正在下载最新更新包，请在服务器端进行安装...";

                srv.updateForNecessary(version).success(function (data) {
                    $scope.loadingState = false;

                    if (data.result) {
                        utils.notify(data.message, 'success');

                        // 动态生成一个form，并通过它实现下载功能
                        var form = $('<form></form>');
                        form.attr('action', '/ExamReport/Download/');
                        form.attr('method', 'post');
                        form.css('display', 'none');
                        var input = $('<input type="hidden" name="filePath" value="' + data.filePath + '" />');
                        form.append(input);
                        form.appendTo('body');
                        form.submit();

                        $scope.close();
                    } else {
                        utils.notify(data.message, 'warning');
                    }
                });
            },
            againLogin: function () {
                // 500毫秒后再次登录
                window.setTimeout(function () {
                    $scope.$emit('login2', true);
                    $scope.close();
                }, 500);
            },
            close: function () {
                $modalInstance.close(true);
            }
        };
        angular.extend($scope, methods);

        $scope.checkForOnLine();
    }]);

    // 配置考点控制器
    myApp.controller('configSteps', ['$scope', '$routeParams', '$modalInstance', 'configService', 'utils', 'params', '$filter', function ($scope, $routeParams, $modalInstance, service, utils, params, $filter) {
        var srv = service.configSrv;

        var methods = {
            connectTest: function () {
                if ($('form#configForm #BatchCode').valid()) {
                    $scope.loadingState = true;

                    var countdown = 5;
                    $scope.linkText = countdown + '...';

                    var interval = window.setInterval(function () {
                        $scope.$apply($scope.linkText = --countdown + '...');

                        if (countdown === 0) {
                            window.clearInterval(interval);
                            utils.notify('连接失败，请检查服务器地址！', 'warning');
                            $scope.$apply($scope.linkText = '测试连接');
                            $scope.$apply($scope.loadingState = false);
                            return;
                        }
                    }, 1000);

                    srv.connectTest($scope.BatchCode).success(function (data) {
                        window.clearInterval(interval);

                        if (data) {
                            $scope.connSuccess = true;
                            $scope.linkText = '';
                        } else {
                            utils.notify('连接失败，请检查服务器地址！', 'warning');
                            $scope.linkText = '测试连接';
                        }
                        $scope.loadingState = false;
                    });
                }
            },
            resetTest: function () {
                $scope.linkText = '测试连接';
                $scope.connSuccess = false;
            },
            save: function () {
                // 第一步提交
                if ($scope.firstStep) {
                    if ($('form#configForm #BatchCode').valid()) {
                        $scope.loadingState = true;

                        var countdown = 5;
                        $scope.linkText = countdown + '...';
                        var interval = window.setInterval(function () {
                            $scope.linkText = --countdown + '...';

                            if (countdown === 0) {
                                window.clearInterval(interval);
                                utils.notify('连接失败，请检查服务器地址！', 'warning');
                                $scope.linkText = '测试连接';
                                $scope.loadingState = false;
                                return;
                            }
                        }, 1000);

                        srv.connectTest($scope.BatchCode).success(function (data) {
                            window.clearInterval(interval);

                            if (data) {
                                $scope.connSuccess = true;
                                $scope.linkText = '';

                                if ($('form#configForm').valid()) {
                                    srv.verification($scope.BatchCode, $scope.validateCode).success(function (data) {
                                        if (data.resultType == 'Success') {
                                            $scope.app = data.app;
                                            $scope.site = data.site;

                                            $scope.firstStep = false;
                                            $scope.firstForm = false;

                                            $scope.submitText = '完成';
                                        } else {
                                            utils.notify(data.message, 'warning');
                                        }

                                        $scope.loadingState = false;
                                    });
                                }
                            } else {
                                utils.notify('连接失败，请检查服务器地址！', 'warning');
                                $scope.linkText = '测试连接';
                            }
                            $scope.loadingState = false;
                        });
                    }
                }

                    // 第二步提交
                else {
                    if ($('form#setPwdForm').valid()) {
                        $scope.loadingState = true;

                        srv.setExamSite($scope.app, $scope.site).success(function (data) {
                            if (data.resultType == 'Success') {
                                $scope.close();

                                $scope.$emit('login', { code: $scope.site.examSiteCode, pwd: $scope.site.sitePwd });
                            } else {
                                utils.notify(data.Message, 'warning');
                            }

                            $scope.loadingState = false;
                        });
                    }
                }
            },
            close: function () {
                $modalInstance.close(true);
            }
        };
        angular.extend($scope, methods);
    }]);

    // 设置当前主办方控制器
    myApp.controller('curAppConfig', ['$scope', '$routeParams', '$modalInstance', 'configService', 'utils', 'params', '$filter', function ($scope, $routeParams, $modalInstance, service, utils, params, $filter) {
        var srv = service.setCurSrv, siteId = params;

        var methods = {
            init: function () {
                srv.getAppList(siteId).success(function (data) {
                    data.unshift({ AppID: 0, AppName: '请选择一个主办方' });

                    $scope.list = data;
                    $scope.curApp = data[0];
                });
            },
            save: function () {
                $scope.loadingState = true;

                var id = $scope.curApp.AppID;
                if (!id) {
                    utils.notify('请选择一个主办方！', 'warning');
                } else {
                    srv.setCurApp(id, siteId).success(function (data) {
                        if (data.resultType == 'Success') {
                            $scope.close();
                            utils.notify('成功设置主办方！', 'success');

                            $scope.$emit('login');
                        } else {
                            utils.notify(data.Message, 'warning');
                        }
                    });
                }
                $scope.loadingState = false;
            },
            close: function () {
                $modalInstance.close(true);
            }
        };
        angular.extend($scope, methods);

        $scope.init();
    }]);
})();